package com.xindacloud.sms.adapter.controller;

import com.clxcommunications.xms.api.BatchDeliveryReport;
import com.xindacloud.sms.adapter.bo.DomesticSmsReportRequestBodyBO;
import com.xindacloud.sms.adapter.component.ReceiveDLRConvertComponent;
import com.xindacloud.sms.adapter.entity.SmsDeliveryReceipt;
import com.xindacloud.sms.adapter.entity.SmsSubmissionRecord;
import com.xindacloud.sms.adapter.service.business.ISmsDeliveryReceiptService;
import com.xindacloud.sms.adapter.service.business.ISmsSubmissionRecordService;
import com.xindacloud.sms.adapter.utils.UnionResultHelp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.util.List;

@Api(tags = {"短信交货报告接口模块"})
@Slf4j
@RestController
@RequestMapping(value = "/api/v1/adapter/sms/dlr")
public class ReceiveDLRController {

    final ISmsDeliveryReceiptService deliveryReceiptService;

    @Autowired
    ISmsSubmissionRecordService smsSubmissionRecordService;

    @Autowired
    ReceiveDLRConvertComponent receiveDLRConvertComponent;

    @Autowired
    public ReceiveDLRController(ISmsDeliveryReceiptService deliveryReceiptService) {
        this.deliveryReceiptService = deliveryReceiptService;
    }

    @ApiOperation(value = "Nexmo交货报告")
    @GetMapping("/webhooks/delivery-receipt")
    public void getDeliveryReceipt(HttpServletRequest req, HttpServletResponse resp) {
        log.info("===== Execute Get Method DLR");
        executeDLR(req, resp);
    }

    @ApiOperation(value = "Nexmo交货报告")
    @PostMapping("/webhooks/delivery-receipt")
    public void postDeliveryReceipt(HttpServletRequest req, HttpServletResponse resp) {
        log.info("===== Execute Post Method DLR");
        executeDLR(req, resp);
    }


    private void executeDLR(HttpServletRequest req, HttpServletResponse resp) {
        @NotNull final SmsDeliveryReceipt nexmoReceiveDLRDTO = receiveDLRConvertComponent.getNexmoReceiveDLRDTO(req);
        boolean resultFlag = deliveryReceiptService.saveDeliveryReceipt(nexmoReceiveDLRDTO);
        log.info("save SmsDeliveryReceipt result:{}", resultFlag);
        final SmsSubmissionRecord build = getSmsSubmissionRecord(nexmoReceiveDLRDTO);
        smsSubmissionRecordService.updateStatusFor(build);
        resp.setStatus(UnionResultHelp.StatusEnum.Success.code());
    }

    @ApiOperation(value = "Sinch交货报告")
    @PostMapping(path = "/sinch/delivery-report")
    public ResponseEntity getSinchReceiveReport(@RequestBody BatchDeliveryReport report) {
        @NotNull final List<SmsDeliveryReceipt> sinchReceiveDLRDTO = receiveDLRConvertComponent.getSinchReceiveDLRDTO(report);
        for (SmsDeliveryReceipt deliveryReceipt : sinchReceiveDLRDTO) {
            deliveryReceiptService.saveDeliveryReceipt(deliveryReceipt);
            final SmsSubmissionRecord build = getSmsSubmissionRecord(deliveryReceipt);
            smsSubmissionRecordService.updateStatusFor(build);
        }
        return ResponseEntity.ok().build();
    }

    @ApiOperation(value = "CM交货报告")
    @GetMapping("/cm/delivery-receipt")
    public ResponseEntity getCMDeliveryReceipt(HttpServletRequest req, HttpServletResponse resp) {

        @NotNull final SmsDeliveryReceipt cmReceiveDLRDTO = receiveDLRConvertComponent.getCMReceiveDLRDTO(req);
        deliveryReceiptService.saveDeliveryReceipt(cmReceiveDLRDTO);
        final SmsSubmissionRecord build = getSmsSubmissionRecord(cmReceiveDLRDTO);
        smsSubmissionRecordService.updateStatusFor(build);
        resp.setStatus(UnionResultHelp.StatusEnum.Success.code());
        return ResponseEntity.ok().build();
    }


    @ApiOperation(value = "国内交货报告")
    @PostMapping("/domestic/delivery-receipt")
    public ResponseEntity geDomesticDeliveryReceipt(@RequestBody DomesticSmsReportRequestBodyBO reportRequestBodyBO, HttpServletResponse resp) {

        @NotNull final SmsDeliveryReceipt domesticReceiveDLRDTO = receiveDLRConvertComponent.getDomesticReceiveDLRDTO(reportRequestBodyBO);
        deliveryReceiptService.saveDeliveryReceipt(domesticReceiveDLRDTO);
        smsSubmissionRecordService.updateStatusFor(getSmsSubmissionRecord(domesticReceiveDLRDTO));
        resp.setStatus(UnionResultHelp.StatusEnum.Success.code());
        return ResponseEntity.ok().build();
    }


    private SmsSubmissionRecord getSmsSubmissionRecord(SmsDeliveryReceipt cmReceiveDLRDTO) {
        return SmsSubmissionRecord.builder()
                .messageId(cmReceiveDLRDTO.getMessageId())
                .sendTo(cmReceiveDLRDTO.getSentTo())
                .network(cmReceiveDLRDTO.getNetworkCode())
                .finalStatus(cmReceiveDLRDTO.getStatus().toLowerCase())
                .errorText(cmReceiveDLRDTO.getReason())
                .build();
    }

}
